﻿using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Web.Mvc;
using System.Web.Routing;
using ShopB2C.Entity;
using ShopB2C.Enums;
using ShopB2C.Helper;
using ShopB2C.Interfaces;
using ShopB2C.ViewModels;

namespace ShopB2C.Controllers.Manager {
    public class BrandController : BaseController {
        private static IBrand _brand;
        private static IClassify _classify;
        private static string _path;
        private const string _moduleKey = "Brands";

        protected override void Initialize(RequestContext requestContext) {
            base.Initialize(requestContext);
            _path = this.Server.MapPath("~/BrandPictures/");
        }

        public BrandController() {
            this.PageSize = 11;
            _brand = DataBaseExecuter.CreateClassByName<IBrand>("Brand");
            _classify = DataBaseExecuter.CreateClassByName<IClassify>("Classify");
        }

        #region Brand

        public ActionResult BrandList([DefaultValue(1)]int number) {
            int pageCount;
            string classifyIdRequest = Request["ClassifyId"];
            int classifyId = string.IsNullOrEmpty(classifyIdRequest)
                ? 0
                : int.Parse(classifyIdRequest);
            return View(new BrandViewModel() {
                BrandList = _brand.GetBrandList(classifyId, this.PageSize, number, out pageCount),
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey),
                PageNumber = number,
                ClassifyId = classifyId,
                Pager = this.CreatePager(Url.Action("BrandList", new {
                    number = "{0}",
                    ClassifyId = classifyId
                }), pageCount, number)
            });
        }

        public ActionResult BrandEdit([DefaultValue(1)]int number, [DefaultValue(0)]int id) {
            List<BrandEntity> listBrand = _brand.GetBrandList(string.Empty);
            return View(new BrandViewModel() {
                Brand = id == 0 ? new BrandEntity() {
                    Url = "http://",
                    Sequence = listBrand != null ? listBrand.Count + 1 : 1,
                } : _brand.GetBrandById(id),
                PageNumber = number,
                ClassifyList = _classify.GetClassifyByModuleKey(_moduleKey)
            });
        }

        [HttpPost]
        public ActionResult BrandEdit([DefaultValue(1)]int number, BrandViewModel bvm, FormCollection fc) {
            BrandEntity be = bvm.Brand;
            // 文件处理
            var file = Request.Files["fLogo"];
            if (file.ContentLength > 0) {
                if (file.ContentLength <= 50 * 1024) {
                    string allowExt = ".gif,.bmp,.jpg,.png,";
                    string ext = Path.GetExtension(file.FileName);
                    string oldName = Path.GetFileNameWithoutExtension(file.FileName);
                    if (allowExt.Contains(ext + ",")) {
                        string fileName = string.Format("{0}{1}{2}",
                            RandomHelper.RandomString(8, RandomType.Letter),
                            oldName.Substring(0, oldName.Length >= 8 ? 8 : oldName.Length),
                            ext);
                        string big = string.Format("{0}{1}", _path, fileName);
                        string small = string.Format("{0}s_{1}", _path, fileName);
                        file.SaveAs(big);
                        MemoryStream ms = ThumbImageHelper.CuteThumbPhoto(88, 31, big, true, true);
                        using (FileStream fs = System.IO.File.Create(small)) {
                            fs.Write(ms.ToArray(), 0, (int)ms.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        if (!string.IsNullOrEmpty(be.Logo)) {
                            System.IO.File.Delete(string.Format("{0}{1}", _path, be.Logo));
                            System.IO.File.Delete(string.Format("{0}s_{1}", _path, be.Logo));
                        }
                        be.Logo = fileName;
                    }
                    else {
                        Methods.Alert("图片类型只能是以 .gif,.bmp,.jpg,.png 结尾的文件!", HttpContext);
                    }
                }
                else {
                    Methods.Alert("图片大小超过 50KB!", HttpContext);
                }
            }

            if (be.BrandId == 0) {
                _brand.BrandAppend(be);
            }
            else {
                _brand.BrandUpdate(be);
            }
            return this.RedirectToAction("BrandEdit", new { number = number, id = be.BrandId });
        }

        public ActionResult BrandDelete(string ids) {
            List<BrandEntity> listBrand = _brand.GetBrandList(ids);
            _brand.BrandDelete(ids);
            // 删除图片文件
            foreach (BrandEntity be in listBrand) {
                if (!string.IsNullOrEmpty(be.Logo)) {
                    System.IO.File.Delete(string.Format("{0}{1}", _path, be.Logo));
                    System.IO.File.Delete(string.Format("{0}s_{1}", _path, be.Logo));
                }
            }

            return RedirectToAction("BrandList");
        }

        [HttpPost]
        public ActionResult BrandEditBatchSeq([DefaultValue(1)]int number, FormCollection fc) {
            _brand.BrandBatchUpdateSequence(fc["cbKey"], fc["tbSequence"]);

            return this.RedirectToAction("BrandList", new { number = number });
        }

        #endregion
    }
}